//=============================================================================
//                              HsimUser.c
//=============================================================================
// AUTHOR      : XENER.COM | kjjeong
// DATE        : 2000.09.19
// DESCRIPTION : 
//=============================================================================
#define _HsimUser_c_

//=============================================================================
//                               I N C L U D E
//=============================================================================
#include	"HsimIncl.h"
#include	"xen_mmc_mng.hpp"
#include	"cmd_agent_mng.hpp"

//=============================================================================
//                              C O N S T A N T
//=============================================================================
#define		MAXLINE		2048
#define		OK			"TURE"
#define		NOK			"FALSE"

//=============================================================================
//                    C L A S S   A N D   S T R U C T U R E
//=============================================================================

//=============================================================================
//                               M A C R O
//=============================================================================

//=============================================================================
//                      S T A T I C   V A R I A B L E
//=============================================================================
xi32	gCimpVersion = 11;
xc8		logfname[32];
FILE	*gfp;
FILE	*fp_sysmsg;
FILE	*fp_mmcmsg;
xui32	gIndex;
xc8		gUsrId[16];

std::string 	g_mmc_recv_buf;	/* FIXME */
boost::mutex	g_mmc_buf_lock;

std::string 	g_alarm_recv_buf;	/* FIXME */
boost::mutex	g_alarm_buf_lock;

//=============================================================================
//                       S T A T I C   F U C T I O N
//=============================================================================

void change_newline(std::string& buf)
{
	char target = '\n';
	std::string goal("\r\n");
	std::size_t f = 0, pos = 0;

	while (1) {
		f = buf.find(target, pos);
		if (f == std::string::npos)
			break;
		buf.replace(f, 1, goal);
		pos = (f+2);
	}
};


void HsimLogOpen()
{
	unlink("user_log");
	unlink("sysmsg.log");
	gfp = fopen("user.log", "a");
	fp_sysmsg = fopen("sysmsg.log", "a");
	fp_mmcmsg = fopen("mmcmsg.log", "a");
}

void handle_echosig(CeMsg *msg, CeEntity *entity, CeConn *conn)
{
	DU_InputStrEcho		cmd_echo;
	DU_InputStrError	cmd_err;
	ClientServerIPC		*echosig = (ClientServerIPC *)(msg->body);
	char buf[512];

	if (echosig->dataType == INPUT_STR_ECHO) {
		memcpy((char *) &cmd_echo, echosig->DataUnit, sizeof(DU_InputStrEcho));
		printf("\n\n\tCMD OK : [%d:%d] %s\n\n", cmd_echo.prn, cmd_echo.IndexJob, cmd_echo.str);
	} else if (echosig->dataType == INPUT_STR_ERROR) {
		/* FIXME */
		memcpy((char *)&cmd_err, echosig->DataUnit, sizeof(DU_InputStrError));
		printf("\n\n\tCMD NOT OK : [%d] %s\n\n", cmd_err.ErrCause, cmd_err.ErrMsg);
		size_t size = sprintf(buf, "CMD NOT OK : [%d] %s\n", cmd_err.ErrCause, cmd_err.ErrMsg);
		{
			boost::mutex::scoped_lock scoped_lock(g_mmc_buf_lock);
			g_mmc_recv_buf.assign(buf, size);
			change_newline(g_mmc_recv_buf);	 
			printf("++++++++++++++++++++++++++++++++++\n");
			printf("check: %s\n", g_mmc_recv_buf.c_str());
			xen_mmc_mng::instance()->push_mmc(g_mmc_recv_buf);	/* FIXME */
			g_mmc_recv_buf.clear();
		}
	} else {
		printf("\t[UserInputStrEcho] invalid echo type (%d)\n", echosig->dataType);
	}
	printf("%s >>", oamHostSysName);
	fflush(stdout);
}

void handle_SystemMsg(CeMsg *msg, CeEntity *entity, CeConn *conn)
{
	xi32		i, j, k, nDevice;
	xc8			szStatus = 0x00;
	xc8			szDevice[36];
	M_InitData	hw_info;
	DU_SysMsg	sysmsg;
	ClientServerIPC	*wincmd = (ClientServerIPC *)(msg->body);

	fflush(stdout);
	if (wincmd->PacketNo < 1) return;
	if (wincmd->PacketNo == 1) printf("\n\n");

	if (wincmd->dataType == INIT_SYSTEM) {
		memcpy((char *)&hw_info, wincmd->DataUnit, sizeof(M_InitData));
	} else {
		{
			boost::mutex::scoped_lock scoped_lock(g_alarm_buf_lock);
			memcpy((char *)&sysmsg, wincmd->DataUnit, sizeof(DU_SysMsg));
			g_alarm_recv_buf.append(sysmsg.SysMsg);

			if (wincmd->next != uTrue) {
				cmd_agent_mng::instance()->send_alarm(g_alarm_recv_buf);
				g_alarm_recv_buf.clear();
			}
			printf("\n>>>>>>> %s", sysmsg.SysMsg);
		}
	}
	if (wincmd->next != uTrue)
		printf("\n\n%s >>", oamHostSysName);
}

void handle_wincmdsig(CeMsg *msg, CeEntity *entity, CeConn *conn)
{
    int    i, j;
    DU_Login 		loginSucc;
    DU_Fail 		loginFail;
    DU_StaData 		data;
    DU_DisUsrHis 	usrhis;
    DU_DisCmdHis 	cmdhis;
    DU_EditDkFile 	editfile, savefile;

	ClientServerIPC	ipc;
	ClientServerIPC	*wincmd = (ClientServerIPC *)(msg->body);

	PDBG("WINCMD: D_TYPE: %d\n", wincmd->dataType);
    switch (wincmd->dataType) {
	case LOGIN :
	case NEW_LOGIN :
	case LOGIN_AND_CHGPWD :
	case NEW_LOGIN_AND_CHGPWD :
		bcp((char *)&loginSucc, wincmd->DataUnit, sizeof(loginSucc));
		entity->entId = myEntId | loginSucc.index;
		gIndex = loginSucc.index;
		printf("\t==================================================\n");
		printf("\t======= LOGIN USER NAME : %-15s ======\n", loginSucc.UserName);
		printf("\t==================================================\n\n");
		printf("%s >>", oamHostSysName);
		break;

	case LOGOUT :
		bcp((char *)&loginSucc, wincmd->DataUnit, sizeof(loginSucc));
		printf("\n");
		printf("\t==================================================\n");
		printf("\t======= LOGOUT USER NAME : %-15s ======\n", loginSucc.UserName);
		printf("\t==================================================\n\n");
		exit(0);
		break;

	case TEXT_CMD :
		if (wincmd->PacketNo == 1) {
			printf("\n");
			//printf("[SIM] overflow    = %d\n", wincmd->overflow);
			//printf("[SIM] next        = %d\n", wincmd->next);
			//printf("[SIM] PacketNo    = %d\n", wincmd->PacketNo);
			//printf("[SIM] dataType= %d\n",wincmd->dataType);
			//printf("-----------------------------------------\n");
		}
		{
			boost::mutex::scoped_lock scoped_lock(g_mmc_buf_lock);
			g_mmc_recv_buf.append((char*)wincmd->DataUnit);
			if (wincmd->next == uFalse) {
				change_newline(g_mmc_recv_buf);
				printf("\n check: %s\n", g_mmc_recv_buf.c_str());
				xen_mmc_mng::instance()->push_mmc(g_mmc_recv_buf);	/* FIXME */
				g_mmc_recv_buf.clear();
				printf("\n%s >>", oamHostSysName);
			}
		}
	    break;

	case FAIL :
            memcpy((char *)&loginFail, wincmd->DataUnit, sizeof(loginFail));
            printf("-----------------------------------------\n");
            printf("[SIM] dataType= %d\n",wincmd->dataType);
            printf("[SIM] Error Code : Type = %d : %d\n", loginFail.ErrorCode,
							loginFail.FailType);
            printf("[SIM] Error Msg  = %s\n", loginFail.ErrorMsg);
            printf("-----------------------------------------\n");
            break;

	default :
		if (wincmd->PacketNo == 1) {
			printf("\n");
			//printf("[SIM] overflow    = %d\n", wincmd->overflow);
			//printf("[SIM] next        = %d\n", wincmd->next);
			//printf("[SIM] PacketNo    = %d\n", wincmd->PacketNo);
			//printf("[SIM] dataType= %d\n",wincmd->dataType);
			//printf("-----------------------------------------\n");
		}
		printf("%s", wincmd->DataUnit);
		if (wincmd->next == uFalse) {
			printf("\n%s >>", oamHostSysName);
		}
		break;
    }
}

void handle_login(CeConn *conn)
{
	int				i, j, retry = 0;
	ClientServerIPC	mmc, mmc_recv;
	GUI_Login 		guiLogin;
	char			user[16], *strPtr,	pwd[16];
	char			*pwdStr;
	const char		*prompt = "PASSWORD : ";

	mmc.overflow = uFalse;
	mmc.next = uFalse;
	mmc.PacketNo = 1;
	mmc.usrType = CLI_USER;
	mmc.dataType = LOGIN;
	memset(guiLogin.UserName, 0, sizeof(guiLogin.UserName));
	memset(guiLogin.oldpasswd, 0, sizeof(guiLogin.oldpasswd));

#if 0
LOGIN_LEVEL:
	retry++;
	if (retry > 5) {
		//close(conn->fd);
		delete conn;
		exit(0);
	}
	printf("\nLOGIN ID : ");
	fflush(stdout);


#ifdef Linux
	if (fgets(guiLogin.UserName,sizeof(guiLogin.UserName),stdin) == NULL)
		goto LOGIN_LEVEL;

	memset(user, 0x00, sizeof(user));
	strncpy(user, guiLogin.UserName, strlen(guiLogin.UserName)-1);
	memset(guiLogin.UserName, 0x00, sizeof(guiLogin.UserName));
	strcpy(guiLogin.UserName, user);
#else
	if (gets(guiLogin.UserName) == NULL)
		goto LOGIN_LEVEL;
#endif
	if (strlen(guiLogin.UserName) == 0)
		goto LOGIN_LEVEL;

	retry = 0;
PWD_LEVEL:
	retry++;
	if (retry > 5) {
		//close(conn->fd);
		delete conn;
		exit(0);
	}
	//////////////////////// only 8 character input
#if defined(Linux)
	pwdStr = getpass(prompt); 
#else
	pwdStr = getpassphrase(prompt);  // changed by csk, 2003.12.16
#endif

	if (pwdStr == NULL || strlen(pwdStr) == 0)
		goto PWD_LEVEL;

	strcpy(guiLogin.oldpasswd, pwdStr);
#endif
	sprintf(guiLogin.UserName, "xener");
	sprintf(guiLogin.oldpasswd, "newdeas");	/* fixed */

	strcpy(mmc.usrName, guiLogin.UserName);
	guiLogin.cimpVer = gCimpVersion;
	bcp(mmc.DataUnit, (char *)&guiLogin, sizeof(struct GUI_Login));
	SendMsgProc(LoginLogout, (char *) &mmc, sizeof(ClientServerIPC), g_HsmbEntId);
	sprintf(gUsrId, "%s\0", guiLogin.UserName);

	printf("\t>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
	printf("\t>>>>>>> SEND LOGIN INFORMATION To SERVER >>>>>>\n");
	printf("\t>>>>>>> WAIT !!! (ABOUT 10 SEC)          >>>>>>\n");
	printf("\t>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n");
	fflush(stdout);
}
